<template>
  <a-space direction="vertical">
    <a-input-search v-if="showKey" v-model:value="searchKey" :placeholder="placeholder" @search="onSearch" @change="onChange" />
    <a-range-picker
      v-if="showDate"
      v-model:value="searchDate"
      class="w-full"
      format="YYYY-MM-DD"
      value-format="YYYY-MM-DD"
      :allow-clear="false"
      @change="onSearch"
    />
  </a-space>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { debounce } from 'lodash-es'

const props = defineProps({
  placeholder: {
    type: String,
    default: '请输入'
  },
  value: {
    type: Object,
    default: () => ({})
  },
  showKey: {
    type: Boolean,
    default: true
  },
  showDate: {
    type: Boolean,
    default: true
  }
})
const getParams = () => {
  return {
    ...(props.showKey ? { searchKey: searchKey.value } : {}),
    ...(props.showDate ? { startDate: searchDate.value?.[0], endDate: searchDate.value?.[1] } : {})
  }
}
const searchKey = ref()
const searchDate = ref([dayjs().format('YYYY-MM-DD'), dayjs(new Date().setDate(new Date().getDate() + 7)).format('YYYY-MM-DD')])
const emit = defineEmits(['search', 'update:value'])
const onSearch = () => {
  const params = getParams()
  emit('update:value', params)
  emit('search', params)
}
const onChange = debounce(() => onSearch(), 200)
onMounted(() => {
  emit('update:value', getParams())
  onSearch()
})
</script>
<style lang="less" scoped></style>
